/**
 *  Copyright (C) 2011  Thomas ROBIN
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package triseries;

import javax.swing.JPopupMenu;

import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.Timer;
import org.jdom.Element;

/**
 * @author tshepo
 * 
 */
public class MyJPopupMenu extends JPopupMenu {
	
	private static final long serialVersionUID = -3000608206481875754L;
	private static final boolean DEBUG = (Main.debug || MyProperties.debug.equalsIgnoreCase("MyJPopupMenu"));
	private JMenuItem infoTriMI;
	private final JMenuItem launchMI;
	private JPopupMenu.Separator jSeparatorFin;
	final Timer timer;
	String recherche = "Recherche.......................";
	public static List<UnwatchEpisode> unwatched;
	TreeMenu tm = null;

	/**
         * 
         */
	public MyJPopupMenu() {
		if(DEBUG) System.err.println("MyJPopupMenu()");

		launchMI = new JMenuItem("Recherche Sous-titres");
		launchMI.setDisabledIcon(new ImageIcon("busy-icon0.gif"));
		this.add(launchMI);

		infoTriMI = new JMenuItem("nouvelle Recherche dans 00:00:00");
		infoTriMI.setSelected(true); // la sourie ne passe plus dessus
		infoTriMI.setArmed(false);

		infoTriMI.setFocusPainted(true);
		this.add(infoTriMI);

		JPopupMenu.Separator jSeparatorDebut = new javax.swing.JPopupMenu.Separator();
		jSeparatorDebut.setName("debut list");
		jSeparatorDebut.setInheritsPopupMenu(true);
		jSeparatorDebut.setMinimumSize(new Dimension(0, 1));
		jSeparatorDebut.setPreferredSize(new Dimension(2, 3));
		this.add(jSeparatorDebut);

		JMenuItem videMI = new JMenuItem("vide");
		videMI.setEnabled(false);
		this.add(videMI);

		jSeparatorFin = new javax.swing.JPopupMenu.Separator();
		jSeparatorFin.setName("fin list");
		jSeparatorFin.setInheritsPopupMenu(true);
		jSeparatorFin.setMinimumSize(new Dimension(0, 1));
		jSeparatorFin.setPreferredSize(new Dimension(2, 3));
		this.add(jSeparatorFin);

		JMenuItem btMI = new JMenuItem("{ betaseries.com }");
		this.add(btMI);

		btMI.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {

				URI uri = null;
				try {
					uri = new URI("https://www.betaseries.com/");
				} catch (URISyntaxException e1) {
					Main.processExeption("MyJPopupMenu.MyJPopupMenu :\n"
					+ e1.getStackTrace().toString());
				}
				try {
					Desktop.getDesktop().browse(uri);
				} catch (IOException e1) {
					Main.processExeption("MyJPopupMenu.MyJPopupMenu :\n"
					+ e1.getStackTrace().toString());
				}

			}
		});

		JMenuItem editMI = new JMenuItem();
		editMI.setText("Editer les propriétés");
		editMI.setName("propriétés");
		this.add(editMI);

		editMI.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				FileAcces.openProperties();
			}
		});

		JPopupMenu.Separator jSeparatorExit = new javax.swing.JPopupMenu.Separator();
		jSeparatorExit.setName("Exit separator");
		jSeparatorExit.setInheritsPopupMenu(true);
		jSeparatorExit.setMinimumSize(new Dimension(0, 1));
		jSeparatorExit.setPreferredSize(new Dimension(2, 3));
		this.add(jSeparatorExit);

		JMenuItem exitMI = new JMenuItem("Exit");
		this.add(exitMI);

		exitMI.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
		});

		timer = new Timer(100, new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				recherche = recherche.charAt(recherche.length() - 1)
						+ recherche.substring(0, recherche.length() - 1);
				launchMI.setText(recherche);
			}
		});

		launchMI.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				Main.nowAction();
			}
		});
	}

	public void startBusyIcon() {
		if(DEBUG) System.err.println("MyJPopupMenu.startBusyIcon()");
		if (!timer.isRunning()) {
			launchMI.setEnabled(false);
			timer.start();
		}
	}

	public void Update() {
		if(DEBUG) System.err.println("MyJPopupMenu.Update()");

		while (!this.getComponent(3).equals(jSeparatorFin)) {
			this.remove(3);
		}
		if (unwatched == null || unwatched.isEmpty()) {
			JMenuItem menuItem = new JMenuItem("vide");
			menuItem.setEnabled(false);
			this.insert(menuItem, 3);
		} else {
			tm = new TreeMenu(unwatched, null);
			tm.MakeTree(this, 3);
		}
		timer.stop();
		launchMI.setEnabled(true);
		launchMI.setText("Recherche Sous-titres");
	}

	void UpdateTiming(int m, int s) {
		int h = m / 60;
		m = m % 60;
		this.infoTriMI.setText(String.format(
				"nouvelle Recherche dans %02d:%02d:%02d", h, m, s));
	}

	void setLocation(TrayIcon trayIcon, MouseEvent e) {
		if(DEBUG) System.err.println("MyJPopupMenu.setLocation()");
		setUnixLocation(trayIcon, e);
		// if(isUnix()) setUnixLocation(trayIcon, e);
		// else this.setLocation(e.getX(), e.getY());
	}

	void setUnixLocation(TrayIcon trayIcon, MouseEvent e) {
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		int x, y;
		if (e.getXOnScreen() < trayIcon.getSize().width) {
			x = trayIcon.getSize().width;
		} else {
			if (e.getXOnScreen() > dim.width - trayIcon.getSize().width) {
				x = dim.width - trayIcon.getSize().width - this.getSize().width;
			} else {
				x = e.getXOnScreen();
				if (e.getX() < trayIcon.getSize().width)
					x -= e.getX();
			}
		}
		if (e.getYOnScreen() < trayIcon.getSize().height) {
			y = trayIcon.getSize().height;
		} else {
			if (e.getYOnScreen() > dim.height - trayIcon.getSize().height) {
				y = dim.height - trayIcon.getSize().height
						- this.getSize().height;
			} else {
				y = e.getYOnScreen();
				if (e.getY() < trayIcon.getSize().height)
					x -= e.getY();
			}
		}
		this.setLocation(x, y);
	}

	public static boolean isUnix() {

		String os = System.getProperty("os.name").toLowerCase();
		return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);

	}

	public void removeEp(String url, int saison, int episode) {
		if(DEBUG) System.err.println("MyJPopupMenu.removeEp("+url+","+saison+","+episode+")");
		while (!this.getComponent(3).equals(jSeparatorFin)) {
			this.remove(3);
		}
		tm.removeEp(url, saison, episode);
		tm.Optimize();
		tm.MakeTree(this, 3);
		if (this.getComponent(3).equals(jSeparatorFin)) {
			JMenuItem menuItem = new JMenuItem("vide");
			menuItem.setEnabled(false);
			this.insert(menuItem, 3);
		}
	}

	public void Update(List<Element> unwatched2) {
		if(DEBUG) System.err.println("MyJPopupMenu.Update(List)");
		Collections.sort(unwatched2, new ElementEpVuSort());
		unwatched = new ArrayList<UnwatchEpisode>();
		for (Element e : unwatched2) {
			unwatched.add(new UnwatchEpisode(e));
		}
		Update();
	}

}
